package bservice

import (
    "fmt"
    "github.com/gomodule/redigo/redis"
    "gonaio_base/constant"
    "sync"
)

var redisMap sync.Map

func (that Service) GetRedis(name string) (c redis.Conn, err error) {
    if name == "" {
        name = bconstant.THE_REDIS_DEFAULT
    }
    value, ok := redisMap.Load(name)
    if ok {
        c = value.(redis.Conn)
        return
    }
    host, port, auth, index, err := that.getRedisConfig(name)
    if err != nil {
        return
    }
    p := redis.Pool{
        Dial: func() (conn redis.Conn, err error) {
            conn, err = redis.Dial("tcp", fmt.Sprintf("%s:%s", host, port))
            if err != nil {
                return
            }
            _, _ = conn.Do("AUTH", auth)
            _, _ = conn.Do("SELECT", index)
            return conn, nil
        },
    }
    c = p.Get()
    redisMap.Store(name, c)
    return
}

func (Service) ClearRedis() {
    redisMap = sync.Map{}
}

func (that Service) getRedisConfig(name string) (host, port, auth, index string, err error) {
    h, err := that.GetConfigHandle()
    if err != nil {
        return
    }
    host = string(h.Get(bconstant.THE_DEFAULT, "redis", name, "host").Bytes())
    port = string(h.Get(bconstant.THE_DEFAULT, "redis", name, "port").Bytes())
    auth = string(h.Get(bconstant.THE_DEFAULT, "redis", name, "auth").Bytes())
    index = string(h.Get(bconstant.THE_DEFAULT, "redis", name, "index").Bytes())
    return
}
